from rest_framework import status, permissions
from rest_framework.response import Response
from rest_framework.decorators import permission_classes
from rest_framework.viewsets import GenericViewSet
from rest_framework import mixins
import requests
from operations.serializers import WeiboReceiveSerializer
from django.core.cache import cache

@permission_classes([permissions.AllowAny])
class WeiboLoginReceive(GenericViewSet, mixins.ListModelMixin):
    serializer_class = WeiboReceiveSerializer

    def list(self, request, *args, **kwargs):
        serializer = WeiboReceiveSerializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        state = serializer.validated_data.get('state')
        code = serializer.validated_data.get('code')

        if cache.has_key(state):
            cache.delete(state)
            apply_access_token_url = "https://api.weibo.com/oauth2/access_token"
            data = {
                'grant_type': "authorization_code",
                'code': code,
                'redirect_uri': "https://dev.qiusuo-mc.cn/operation-manage/weibo-receive",
                'client_id': "3064679309",
                'client_secret': "c58e5efd27b8aa9b4afe833659818b44"
            }
            access_token_res = requests.post(apply_access_token_url, data=data).json()
            access_token = access_token_res["access_token"]
            weibo_id = access_token_res["uid"]
            data = {'success':True}
            data["code"] = 201

            get_userinfo_url = "https://api.weibo.com/2/users/show.json"
            getparams = {
                'access_token': access_token,
                'uid': weibo_id
            }

            username = requests.get(get_userinfo_url, params=getparams).json()["name"]
            weibouserlogin_url = "https://dev.qiusuo-mc.cn/operation-manage/weibouser-login/"
            login_data = {
                'weibo_id': weibo_id,
                'username': username
            }
            result = requests.post(url=weibouserlogin_url, data=login_data).json()

            data["result"] = result["result"]
            data["token"] = result['token']

            return Response(data=data, status=status.HTTP_201_CREATED)

        else :
            data = {'result': 'unknown attack'}
            return Response(data=data, status=status.HTTP_201_CREATED)
